'use strict';
const Service = require('egg').Service;
const { Op, where, Sequelize } = require('sequelize');
const ulid = require('../public/ulid');
// var dayjs = require('dayjs');
class userManagementService extends Service {
  async changeUser(val) {
    try {
      this.ctx.modelmysql.UserManagement.update(
        { ...val},
        { where: { _id:val._id} }
      );
      return 'success';
    } catch (err) {
      return err;
    }
  }

  async list(val, tid) {
    let result = null;
    let where = JSON.parse(JSON.stringify(val));
    delete where.limit;
    delete where.page;
    delete where.total;
    //  delete where.timeOut
    where.tid = tid;
    for (let i in where) {
      if (!where[i]) {
        delete where[i];
      }
    }
    if (where.name) {
      where.name = { [Op.like]: '%' + where.name + '%' };
    }
    if (where.address) {
      where.address = { [Op.like]: '%' + where.address + '%' };
    }
    if (where.phone) {
      where.phone = { [Op.like]: '%' + where.phone + '%' };
    }
    if (where.timeOut) {
      where.outTime = { [Op.gte]: where.timeOut };
      delete where.timeOut;
    }
    try {
      result = await this.ctx.modelmysql.UserManagement.findAndCountAll({
        where,
        offset: parseInt((val.page - 1) * val.limit),
        limit: parseInt(val.limit),
      });
      return result;
    } catch (err) {
      result = err;
      return result;
    }
  }

  async createGroup(input) {
    const result = {
      code: '',
      msg: 'success',
      id: '',
    };
    const tid = input.tid;

    try {
      await this.ctx.modelmysql.UserGroup.create({
        id: ulid.ulid(),
        name: input.groupName,
        tid,
      });

      return result;
    } catch (error) {
      result.msg = error;
      return result;
    }
  }
  async checkGroupName(name) {
    let result = await this.ctx.modelmysql.UserGroup.findOne({
      where: {
        name,
      },
    });

    return result;
  }

  async addGroup(input) {
    const result = {
      code: '',
      msg: 'success',
      id: '',
    };
    const tid = input.tid;
    try {
      input.userList.forEach(async (v) => {
        console.log(v);
        await this.ctx.modelmysql.UserManagement.update(
          { groupId: input.groupId },
          { where: { _id: v._id } }
        );
      });
    } catch (err) {
      return err;
    }
    return 'success';

    // try {
    //   await this.ctx.model.OnuList.updateMany({tid,_id:{$in:input.onus}},{$set:{onugroupId:input.group}})
    // } catch (error) {
    //   result.msg = error;

    // }
    // return result;
  }
  // bind ONU
  async bindingONU(val) {
    let msg = 'success'
    try {
      let {macAddress,bandWidth,CATV,SN,outTime,_id,onuId} = val
     await  this.ctx.modelmysql.UserManagement.update({macAddress,bandWidth,CATV,SN,outTime,onuId},{where: { _id}})
     } catch (error) {
       msg = error
    }
     return msg
  }
}

module.exports = userManagementService;
